// dao/proxyConfig.js
import { connect } from '../db'

// 获取代理配置
export function getProxyConfig() {
  const db = connect()
  const result = db.prepare('SELECT * FROM proxy_config WHERE id = 1').get()
  return result || {
    id: 1,
    proxy_url: 'https://apiproxcy.chen88.top/v1',
    enabled: 0,
    created_at: Date.now(),
    updated_at: Date.now()
  }
}

// 更新代理配置
export function updateProxyConfig(proxyUrl, enabled) {
  const db = connect()
  const now = Date.now()

  // 检查是否已有配置
  const existing = db.prepare('SELECT * FROM proxy_config WHERE id = 1').get()

  if (existing) {
    // 更新现有配置
    const info = db.prepare(
      'UPDATE proxy_config SET proxy_url = ?, enabled = ?, updated_at = ? WHERE id = 1'
    ).run(proxyUrl, enabled ? 1 : 0, now)
    return info
  } else {
    // 创建新配置
    const info = db.prepare(
      'INSERT INTO proxy_config (id, proxy_url, enabled, created_at, updated_at) VALUES (1, ?, ?, ?, ?)'
    ).run(proxyUrl, enabled ? 1 : 0, now, now)
    return info
  }
}

// 切换代理状态
export function toggleProxyStatus(enabled) {
  const db = connect()
  const now = Date.now()

  // 检查是否已有配置
  const existing = db.prepare('SELECT * FROM proxy_config WHERE id = 1').get()

  if (existing) {
    // 更新现有配置
    const info = db.prepare(
      'UPDATE proxy_config SET enabled = ?, updated_at = ? WHERE id = 1'
    ).run(enabled ? 1 : 0, now)
    return info
  } else {
    // 使用默认URL创建新配置
    return updateProxyConfig('https://apiproxcy.chen88.top/v1', enabled)
  }
}
